export function showFileUploader({
  multiple = false,
  accept = '*'
} = {}): Promise<File[]> {
  return new Promise((resolve) => {
    // 创建一个input元素
    const fileInput = document.createElement('input')
    fileInput.type = 'file'
    fileInput.multiple = multiple
    fileInput.accept = accept

    // 设置选择文件后的回调函数
    fileInput.addEventListener('change', onChange)
    function onChange() {
      resolve(Array.from(fileInput.files || []))
      fileInput.removeEventListener('change', onChange)

    }


    // 触发选择文件的窗口
    fileInput.click()
  })
}

export function loadImg(src: string): Promise<HTMLImageElement> {
  return new Promise((resolve) => {
    const img = new Image()

    img.onload = function () {
      resolve(img)
    }
    img.src = src
  })

}

export function getImageData(img: HTMLImageElement, maxWidth?: number) {
  const canvas = document.createElement('canvas');


  const ctx = canvas.getContext('2d')!;
  let width = img.width
  let height = img.height
  if (maxWidth) {
    const ratio = img.width / img.height;
    width = img.width > img.height ? maxWidth : maxWidth * ratio;
    height = img.width > img.height ? maxWidth / ratio : maxWidth;
  }

  canvas.width = width;
  canvas.height = height;
  ctx.drawImage(img, 0, 0, width, height);

  return ctx.getImageData(0, 0, width, height);
}